<script setup>
import { onMounted, nextTick, ref, reactive, watch, computed, watchEffect } from 'vue'
import { GetALLLiveLoc_JK, getCameraIndexIdByShipName, getKeepTime, getReport, upLoadPng, clearPng, getReportFile } from '../network/net.js'
import { formatTime, getDay } from '../utils/cTime.js'
// import keepData from '../assets/json/keep.json'
import * as echarts from 'echarts'
// 加载
import { ElLoading } from 'element-plus'

const fullscreenLoading = ref(false)
let formData = {
    date1: '',
    date2: '',
    str2: '',
    numAll: 0,
    num1: 0,
    num2: 0,
    num3: 0,
    ones: [],
    twos: [],
}
let chartArr = new Array(300)
let chartArr1 = new Array(300)

onMounted(() => {

    // - 24 * 60 * 60 * 1000
    dateOne.value = formatTime(new Date().getTime())
    dateOne.value = dateOne.value.split(' ')[0] + ' 06:00:00'

    dateTwo.value = formatTime(new Date().getTime())
    dateTwo.value = dateTwo.value.split(' ')[0] + ' 20:00:00'


    // console.log(getDay(dateOne.value,-7));
    return

    const data = {
        startTime: dateOne.value + ' 00:00:00',
        endTime: dateOne.value + ' 23:59:59',
    }
    let startDate = data.startTime.split(' ')[0]
    let endDate = data.endTime.split(' ')[0]

    let startDateArr = startDate.split('-')
    let endDateArr = endDate.split('-')
    let startDateCh = `${startDateArr[0]}年${startDateArr[1]}月${startDateArr[2]}日`
    let endDateCh = `${endDateArr[0]}年${endDateArr[1]}月${endDateArr[2]}日`
    formData = {
        date1: startDateCh,
        date2: endDateCh,
        str2: '',
        numAll: 0,
        num1: 0,
        num2: 0,
        num3: 0,
        ones: [],
        twos: [],
    }
    let index = 1
    let index2 = 1
    let index22 = 1
    let strArr = []
    console.log(keepData);
    // keepData排序，keepTime为暂无数据和离线时间比例大于0.9的排在最后
    keepData.sort((a, b) => {
        if (a.keepTime == '暂无数据' && b.keepTime != '暂无数据') {
            return 1
        } else if (a.keepTime != '暂无数据' && b.keepTime == '暂无数据') {
            return -1
        } else if (a.keepTime != '暂无数据' && b.keepTime != '暂无数据') {
            let onlineTimeA = 0
            let offlineTimeA = 0
            a.keepTime.forEach(item => {
                if (item[2] == '在线') {
                    onlineTimeA += item[1]
                } else {
                    offlineTimeA += item[1]
                }
            })
            let onlineTimeB = 0
            let offlineTimeB = 0
            b.keepTime.forEach(item => {
                if (item[2] == '在线') {
                    onlineTimeB += item[1]
                } else {
                    offlineTimeB += item[1]
                }
            })
            if (offlineTimeA / (onlineTimeA + offlineTimeA) > offlineTimeB / (onlineTimeB + offlineTimeB)) {
                return 1
            } else {
                return -1
            }
        }
    })
    keepData.forEach((item, idx) => {
        if (item.keepTime == '暂无数据') {
            strArr.push(item.name)
        } else {
            let onlineTime = 0
            let offlineTime = 0
            let t = []
            item.keepTime.forEach((item2, idx2) => {
                if (item2[2] == '在线') {
                    onlineTime += item2[1]
                } else {
                    offlineTime += item2[1]
                }
                t.push({
                    k1: ++idx2 + '',
                    k2: item2[0],
                    k3: item2[1].toFixed(2) + '小时',
                    k4: item2[2],
                })
            })

            if (offlineTime / (onlineTime + offlineTime) > num.value) {
                let str = ''
                if (onlineTime == 0) {
                    str = '一直离线'
                } else {
                    str = `该船舶于${startDateCh} 0时至${endDateCh} 0时，在线时长共计${onlineTime.toFixed(2)}小时，离线时长共计${offlineTime.toFixed(2)}小时，离线时间对比如图所示。`
                }

                if (onlineTime != 0) {
                    chartArr1[index22 - 1] = echarts.init(document.getElementById('chartTwo' + (index22 - 1)))
                    // 绘制饼状图
                    chartArr1[index22 - 1].setOption({
                        title: {
                            text: '船舶离线在线时间对比',
                            left: 'center',
                            top: 10,
                            textStyle: {
                                color: '#000',
                                fontSize: 14,
                            }
                        },
                        grid: {
                            top: 20,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            containLabel: true
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        series: [
                            {
                                name: '离线时间对比',
                                type: 'pie',
                                radius: '70%',
                                center: ['50%', '60%'],
                                data: [
                                    { value: onlineTime, name: '在线' },
                                    { value: offlineTime, name: '离线' },
                                ],
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                label: {
                                    show: true,
                                    position: 'inside',
                                    formatter: function (params) {
                                        return params.name + ' : ' + params.value.toFixed(2) + '小时'
                                    }
                                },
                                // 不显示动画
                                animation: false,
                            }
                        ]
                    })
                    index22++
                }


                formData.twos.push({
                    title: `1.2.${index2}${item.name}`,
                    str: str,
                    isDetail: false,
                    isT: str == '一直离线' ? false : true,
                    t: t,
                    img: index22 - 2
                })
                index2++
            } else if (offlineTime == 0) {

            } else {
                chartArr[index - 1] = echarts.init(document.getElementById('chart' + (index - 1)))
                // 绘制饼状图
                chartArr[index - 1].setOption({
                    title: {
                        text: '船舶离线在线时间对比',
                        left: 'center',
                        top: 10,
                        textStyle: {
                            color: '#000',
                            fontSize: 14,
                        }
                    },
                    grid: {
                        top: 20,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        containLabel: true
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    series: [
                        {
                            name: '离线时间对比',
                            type: 'pie',
                            radius: '70%',
                            center: ['50%', '60%'],
                            data: [
                                { value: onlineTime, name: '在线' },
                                { value: offlineTime, name: '离线' },
                            ],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            },
                            label: {
                                show: true,
                                position: 'inside',
                                formatter: function (params) {
                                    return params.name + ' : ' + params.value.toFixed(2) + '小时'
                                }
                            },
                            // 不显示动画
                            animation: false,
                        }
                    ]
                })

                formData.ones.push({
                    title: `1.1.${index}${item.name}`,
                    str: `该船舶于${startDateCh} 0时至${endDateCh} 0时，在线时长共计${onlineTime.toFixed(2)}小时，离线时长共计${offlineTime.toFixed(2)}小时，离线时间对比如图所示。`,
                    isDetail: true,
                    isT: true,
                    t: t,
                    img: index - 1
                })
                index++
            }
        }

    })

    formData.numAll = keepData.length
    formData.num1 = formData.ones.length
    formData.num2 = formData.twos.length
    formData.num3 = strArr.length
    if (strArr.length > 0) {
        formData.str2 = strArr.join('、') + '。'
    }
    return

    data.startTime = data.startTime.split(' ')[0] + ' 00:00:00'
    data.endTime = data.startTime.split(' ')[0] + ' 23:59:59'
    GetALLLiveLoc_JK().then(res => {
        fishers.value = res.data.data[2].shipdata.map(item => {
            return {
                name: item.basicinfor.shipname,
                id: item.basicinfor.shipid,
            }
        })
        let allP = []
        fishers.value.forEach(item => {
            allP.push(getCameraIndexIdByShipName({ shipName: item.name }))
        })
        Promise.all(allP).then(async (res2) => {
            res2.forEach((item, index) => {
                fishers.value[index].id = item.data[0].cameraindexid
            })
            let allP2 = []
            await fishers.value.forEach((item, idx) => {
                if (item.id.length > 8) {
                    ((idx) => {
                        let p = getKeepTime({
                            indexId: item.id,
                            startTime: data.startTime,
                            endTime: data.endTime,
                        }).then(res3 => {
                            fishers.value[idx].keepTime = res3.data.result
                        }).catch(err => {
                            fishers.value[idx].keepTime = '暂无数据'
                        })
                        allP2.push(p)
                    })(idx);
                } else {
                    fishers.value[idx].keepTime = '暂无数据'
                }
            })
            Promise.all(allP2).then(() => {
                console.log(fishers.value);
            })
        })
    })
})

const date = reactive({
    startTime: '',
    endTime: '',
})
let loading
const getData = () => {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
    })
    // 获取dateOne的下一天
    // const data = {
    //     startTime: getDay(dateOne.value, -1) + ' 00:00:00',
    //     endTime: dateOne.value + ' 00:00:00',
    // }
    const data = {
        startTime: dateOne.value,
        endTime: dateTwo.value,
    }
    console.log(data);
    // data.startTime = data.startTime.split(' ')[0] + ' 00:00:00'
    // data.endTime = data.startTime.split(' ')[0] + ' 23:59:59'
    GetALLLiveLoc_JK().then(res => {
        fishers.value = res.data.data[2].shipdata.map(item => {
            return {
                name: item.basicinfor.shipname,
                id: item.basicinfor.shipid,
            }
        })
        let allP = []
        fishers.value.forEach(item => {
            allP.push(getCameraIndexIdByShipName({ shipName: item.name }))
        })
        Promise.all(allP).then(async (res2) => {
            res2.forEach((item, index) => {
                fishers.value[index].id = item.data[0].cameraindexid
            })
            let allP2 = []
            await fishers.value.forEach((item, idx) => {
                if (item.id.length > 8) {
                    ((idx) => {
                        let p = getKeepTime({
                            indexId: item.id,
                            startTime: data.startTime,
                            endTime: data.endTime,
                        }).then(res3 => {
                            fishers.value[idx].keepTime = res3.data.result
                        }).catch(err => {
                            fishers.value[idx].keepTime = '暂无数据'
                        })
                        allP2.push(p)
                    })(idx);
                } else {
                    fishers.value[idx].keepTime = '暂无数据'
                }
            })
            Promise.all(allP2).then(() => {
                let keepData = fishers.value
                // console.log(fishers.value);
                // const data = {
                //     startTime: dateOne.value + ' 00:00:00',
                //     endTime: dateOne.value + ' 23:59:59',
                // }
                let startDate = data.startTime.split(' ')[0]
                let endDate = data.endTime.split(' ')[0]

                let startDateArr = startDate.split('-')
                let endDateArr = endDate.split('-')
                let startDateCh = `${startDateArr[0]}年${startDateArr[1]}月${startDateArr[2]}日`
                let endDateCh = `${endDateArr[0]}年${endDateArr[1]}月${endDateArr[2]}日`
                // console.log(startDateCh,endDateCh);
                formData = {
                    date1: startDateCh,
                    date2: endDateCh,
                    str2: '',
                    numAll: 0,
                    num1: 0,
                    num2: 0,
                    num3: 0,
                    ones: [],
                    twos: [],
                }
                let index = 1
                let index2 = 1
                let index22 = 1
                let strArr = []
                // console.log(keepData);
                // keepData排序，keepTime为暂无数据和离线时间比例大于0.9的排在最后
                keepData.sort((a, b) => {
                    if (a.keepTime == '暂无数据' && b.keepTime != '暂无数据') {
                        return 1
                    } else if (a.keepTime != '暂无数据' && b.keepTime == '暂无数据') {
                        return -1
                    } else if (a.keepTime != '暂无数据' && b.keepTime != '暂无数据') {
                        let onlineTimeA = 0
                        let offlineTimeA = 0
                        a.keepTime.forEach(item => {
                            if (item[2] == '在线') {
                                onlineTimeA += item[1]
                            } else {
                                offlineTimeA += item[1]
                            }
                        })
                        let onlineTimeB = 0
                        let offlineTimeB = 0
                        b.keepTime.forEach(item => {
                            if (item[2] == '在线') {
                                onlineTimeB += item[1]
                            } else {
                                offlineTimeB += item[1]
                            }
                        })
                        if (offlineTimeA / (onlineTimeA + offlineTimeA) > offlineTimeB / (onlineTimeB + offlineTimeB)) {
                            return 1
                        } else {
                            return -1
                        }
                    }
                })
                keepData.forEach((item, idx) => {
                    if (item.keepTime == '暂无数据') {
                        strArr.push(item.name)
                    } else {
                        let onlineTime = 0
                        let offlineTime = 0
                        let t = []
                        item.keepTime.forEach((item2, idx2) => {
                            if (item2[2] == '在线') {
                                onlineTime += item2[1]
                            } else {
                                offlineTime += item2[1]
                            }
                            t.push({
                                k1: ++idx2 + '',
                                k2: item2[0],
                                k3: item2[1].toFixed(2) + '小时',
                                k4: item2[2],
                            })
                        })

                        if (offlineTime / (onlineTime + offlineTime) > num.value) {
                            let str = ''
                            if (onlineTime == 0) {
                                str = '一直离线'
                            } else {
                                str = `该船舶于${startDateCh} 0时至${endDateCh} 0时，在线时长共计${onlineTime.toFixed(2)}小时，离线时长共计${offlineTime.toFixed(2)}小时，离线时间对比如图所示。`
                            }

                            if (onlineTime != 0) {
                                chartArr1[index22 - 1] = echarts.init(document.getElementById('chartTwo' + (index22 - 1)))
                                // 绘制饼状图
                                chartArr1[index22 - 1].setOption({
                                    title: {
                                        text: '船舶离线在线时间对比',
                                        left: 'center',
                                        top: 10,
                                        textStyle: {
                                            color: '#000',
                                            fontSize: 14,
                                        }
                                    },
                                    grid: {
                                        top: 20,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        containLabel: true
                                    },
                                    tooltip: {
                                        trigger: 'item',
                                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                                    },
                                    series: [
                                        {
                                            name: '离线时间对比',
                                            type: 'pie',
                                            radius: '70%',
                                            center: ['50%', '60%'],
                                            data: [
                                                { value: onlineTime, name: '在线' },
                                                { value: offlineTime, name: '离线' },
                                            ],
                                            emphasis: {
                                                itemStyle: {
                                                    shadowBlur: 10,
                                                    shadowOffsetX: 0,
                                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                                }
                                            },
                                            label: {
                                                show: true,
                                                position: 'inside',
                                                formatter: function (params) {
                                                    return params.name + ' : ' + params.value.toFixed(2) + '小时'
                                                }
                                            },
                                            // 不显示动画
                                            animation: false,
                                            color: ['#006343', '#de0212']
                                        }
                                    ]
                                })
                                index22++
                            }


                            formData.twos.push({
                                title: `1.2.${index2}${item.name}`,
                                str: str,
                                isDetail: false,
                                isT: str == '一直离线' ? false : true,
                                t: t,
                                img: index22 - 2
                            })
                            index2++
                        } else if (offlineTime == 0) {

                        } else {
                            console.log(index);
                            chartArr[index - 1] = echarts.init(document.getElementById('chart' + (index - 1)))
                            // 绘制饼状图
                            chartArr[index - 1].setOption({
                                title: {
                                    text: '船舶离线在线时间对比',
                                    left: 'center',
                                    top: 10,
                                    textStyle: {
                                        color: '#000',
                                        fontSize: 14,
                                    }
                                },
                                grid: {
                                    top: 20,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    containLabel: true
                                },
                                tooltip: {
                                    trigger: 'item',
                                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                                },
                                series: [
                                    {
                                        name: '离线时间对比',
                                        type: 'pie',
                                        radius: '70%',
                                        center: ['50%', '60%'],
                                        data: [
                                            { value: onlineTime, name: '在线' },
                                            { value: offlineTime, name: '离线' },
                                        ],
                                        emphasis: {
                                            itemStyle: {
                                                shadowBlur: 10,
                                                shadowOffsetX: 0,
                                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                                            }
                                        },
                                        label: {
                                            show: true,
                                            position: 'inside',
                                            formatter: function (params) {
                                                // return params.name + ' : ' + params.value.toFixed(2) + '小时\n'
                                                return `\n${params.name} : ${params.value.toFixed(2)}小时\n`
                                            }
                                        },
                                        labelLayout: { // 环形图标签的布局
                                            hideOverlap: false,
                                        },
                                        avoidLabelOverlap: true, // 防止标签重叠
                                        // 不显示动画
                                        animation: false,
                                        color: ['#006343', '#de0212']

                                    }
                                ]
                            })

                            formData.ones.push({
                                title: `1.1.${index}${item.name}`,
                                str: `该船舶于${startDateCh} 8时至${endDateCh} 24时，在线时长共计${onlineTime.toFixed(2)}小时，离线时长共计${offlineTime.toFixed(2)}小时，离线时间对比如图所示。`,
                                isDetail: true,
                                isT: true,
                                t: t,
                                img: index - 1
                            })
                            index++
                        }
                    }

                })

                formData.numAll = keepData.length
                formData.num1 = formData.ones.length
                formData.num2 = formData.twos.length
                formData.num3 = strArr.length
                if (strArr.length > 0) {
                    formData.str2 = strArr.join('、') + '。'
                }

                exportReport()
            })
        })
    })
}

const base64ToBlob = (code) => {
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], { type: contentType });
}

const fishers = ref([])

const exportReport = async () => {
    await nextTick()
    let allP = []
    chartArr.forEach((item, idx) => {
        let fileBase64 = item.getDataURL({ pixelRatio: 2, excludeComponents: ['toolbox'] })
        // 转为blob
        let blob = base64ToBlob(fileBase64)
        // 转为file
        // 保持唯一性，使用时间戳
        let fileName = Date.now() + ".png"
        let file = new File([blob], fileName, { type: "image/png" })
        let formDataFile = new FormData();
        formDataFile.append('file', file);
        let fItem = formData.ones.find(item => item.img == idx)
        fItem.img = fileName
        allP.push(upLoadPng(formDataFile))
    })

    chartArr1.forEach((item, idx) => {
        let fileBase64 = item.getDataURL({ pixelRatio: 2, excludeComponents: ['toolbox'] })
        // 转为blob
        let blob = base64ToBlob(fileBase64)
        // 转为file
        // 保持唯一性，使用时间戳
        let fileName = Date.now() + ".png"
        let file = new File([blob], fileName, { type: "image/png" })
        let formDataFile = new FormData();
        formDataFile.append('file', file);
        let fItem = formData.twos.find(item => item.img == idx)
        fItem.img = fileName
        allP.push(upLoadPng(formDataFile))

        // upLoadPng(formDataFile).then(res => {
        //     console.log(res);
        // })
    })

    Promise.all(allP).then(() => {
        getReport(formData).then(res => {
            // console.log(res);
            let name = res.data
            getReportFile(res.data).then(res => {
                // 下载文件
                const url = window.URL.createObjectURL(new Blob([res.data]))
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', name)
                document.body.appendChild(link)
                link.click()
                window.URL.revokeObjectURL(url)

            })
            clearPng()
        }).finally(() => {
            // fullscreenLoading.value = false
            loading.close()
            // window.location.reload()
        })
    })
}

const num = ref(0.9)
const dateOne = ref('')
const dateTwo = ref('')
</script>

<template>
    <div id="report">
        <!-- 日期选择器 -->
         <div style="display: flex;align-items: center;">
            <el-date-picker v-model="dateOne" type="datetime" placeholder="选今天吧" value-format="YYYY-MM-DD HH:mm:ss"
            style="margin: 10px;" />
            到
            <el-date-picker v-model="dateTwo" type="datetime" placeholder="选今天吧" value-format="YYYY-MM-DD HH:mm:ss"
            style="margin: 10px;" />
         </div>

        <div style="margin: 10px;">
            <span>认定为疑似关闭设备船舶的离线比例：</span>
            <!-- 数字选择器 0-1 -->
            <el-input-number v-model="num" :precision="2" :step="0.05" :max="1" :min="0" />
        </div>
        <div style="display: flex;overflow: auto;flex-direction: column;width: 100%;">
            <div style="display: flex;overflow: auto;">
                <div v-for="(item, idx) in chartArr" :id="'chart' + idx"
                    style="height: 180px;width: 180px;flex-shrink: 0;">
                </div>
            </div>

            <div style="display: flex;overflow: auto;">
                <div v-for="(item, idx) in chartArr1" :id="'chartTwo' + idx"
                    style="height: 180px;width: 180px;flex-shrink: 0;">

                </div>
            </div>

        </div>

        <el-button type="primary" size="default" @click="getData"
            style="position: fixed;right: 0;bottom: 0;margin: 10px;">导出报表</el-button>

    </div>
</template>

<style lang="less" scoped>
#report {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}
</style>